#!/bin/bash


echo "456789" | sudo -S nohup /home/wwwroot/pavgps/remote_start.sh > /dev/null 2>&1 &


funRun(){
	cmd1="ps -ef | grep '$1' | grep -v grep | wc -l"
	count=`eval $cmd1`
	echo $count
    if [ $count -eq 0 ];then
        cmd2="echo "456789" | sudo -S nohup $1 > /dev/null 2>&1 &"
  	res=`eval $cmd2`
    fi
}

funRunRover(){
#	funRun '/home/wwwroot/pavgps/gpsrover'
	funRun 'php /home/wwwroot/pavgps/gpstmp-sensor.php'
	funRun 'php /home/wwwroot/pavgps/datasync.php'
	funRun 'python /home/wwwroot/pavgps/drct.py'
#	funRun 'python /home/wwwroot/pavgps/temperature.py'
	funRun 'python /home/wwwroot/pavgps/encoder.py'
#	funRun 'php /home/wwwroot/pavgps/rtksync.php'
	funRun 'php /home/wwwroot/pavgps/led.php'
	funRun 'python /home/wwwroot/pavgps/gpsrover.py'
#	funRun 'python /home/wwwroot/pavgps/monitor.py'
	sleep 5;
}

funStopRover(){
	ps aux | grep 'control.sh start' | awk '{print $2}'| xargs sudo kill
	ps aux | grep gpstmp | awk '{print $2}'| xargs sudo kill
	ps aux | grep datasync | awk '{print $2}'| xargs sudo kill
	ps aux | grep drct | awk '{print $2}'| xargs sudo kill
#	ps aux | grep temperature | awk '{print $2}'| xargs sudo kill
	ps aux | grep encoder | awk '{print $2}'| xargs sudo kill
	ps aux | grep downapp.php | awk '{print $2}'| xargs sudo kill
	ps aux | grep led.php | awk '{print $2}'| xargs sudo kill
#	ps aux | grep rtksync.php | awk '{print $2}'| xargs sudo kill
	ps aux | grep gpsrover | awk '{print $2}'| xargs sudo kill
}

funRunBaseStation(){
	funRun 'python /home/wwwroot/pavgps/baseStation.py'
	funRun 'python /home/wwwroot/pavgps/monitor.py'
	ps aux | grep 'chrome' | awk '{print $2}'| xargs sudo kill
	sleep 5;
}

funStopBaseStation(){
	ps aux | grep 'control.sh start' | awk '{print $2}'| xargs sudo kill
	ps aux | grep 'baseStation' | awk '{print $2}'| xargs sudo kill
#	ps aux | grep 'monitor' | awk '{print $2}'| xargs sudo kill
}


gpstype=$(cat /home/wwwroot/pavgps/gpstype.cnf)
if [ $1 == "start" ];then
	echo "start.."
	while true; do
		if [ $gpstype == 1 ];then
			echo " Rover"
			funRunRover
		else
			echo " BaseStation"
			funRunBaseStation
			sleep 10;
		fi
		sleep 5
	done
fi



if [ $1 == "stop" ];then
echo "stop.."
	if [ $gpstype == 1 ];then
		funStopRover
	else
		funStopBaseStation
	fi
fi


if [ $1 == "restart" ];then
ps aux | grep client_remote | awk '{print $2}'| xargs sudo kill
fi
